#include <vector>
#include <iostream>
#include "InetAddr.hpp"
#include "Common.hpp"
#include <functional>
#include "ThreadPool.hpp"


using task_t = std::function<void()>;

class Route
{

public:
    Route()
    {
    }

    void Offline(InetAddr who)
    {
        auto iter = _online_user.begin();
        while (iter != _online_user.end())
        {
            if (*iter == who)
            {
                _online_user.erase(iter);
                break;
            }
        }
    }

    void JudgeOnline(InetAddr who)
    {
        for (auto e : _online_user)
        {
            if (who == e)
                break;
        }
        _online_user.push_back(who);
    }

    void ForwardHelper(int sockfd, InetAddr& who, const std::string &message)
    {
        std::string send_message = "[" + who.AddrString() + "]say#" + message;

        for (auto e : _online_user)
        {
            struct sockaddr_in other_client = e.Addr();
            int n = ::sendto(sockfd, send_message.c_str(), send_message.size(), 0, (struct sockaddr *)&other_client, sizeof(other_client));
            if(n < 0)
            {
                perror("Route message");
                exit(FORWARD_ERROR);
            }
        }
    }

    // 转发功能
    void Forward(int sockfd, std::string &message, InetAddr who)
    {
        // 确定是否在线
        JudgeOnline(who);

        // 下线
        if (message == "QUIT" || message == "Q")
        {
            Offline(who);
        }

        // 转发消息
        // ForwardHelper(sockfd, who, message); // -> sockfd
        // ->引入线程池
        task_t task = std::bind(&Route::ForwardHelper,this, sockfd, who, message);
        ThreadPool<task_t>::GetInstance()->Equeue(task);
        
    }

    ~Route()
    {
    }

private:
    std::vector<InetAddr> _online_user; // 在线用户列表
    pthread_mutex_t _mutex;
};